package com.heg.bk.util.wxpay;

import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
import org.xml.sax.InputSource;

import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.heg.bk.util.HttpHelpUtils;

public class CommonUtils {
	
	private static Logger logger = Logger.getLogger(CommonUtils.class);
	
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

	public static Map<String, String> scanPay_wxpay(String appid, String buss_num, String orderid, String total_fee, 
			String trade_type, String notify_url, String device_info, String fee_type, String spbill_create_ip, String openid){
		Map<String, String> resultMaps = new HashMap<String, String>();
		SortedMap<String, String> payParams = new TreeMap<String, String>();
		payParams.put("appid", appid); //app ID
		payParams.put("mch_id", buss_num); //商户号
		payParams.put("device_info", device_info); // 设备类型
		payParams.put("nonce_str", RandomStringUtils.randomAlphanumeric(16));//随机字符串
		payParams.put("body", "微信支付-" + orderid);//商品描述
		payParams.put("out_trade_no", String.valueOf(orderid)); //订单号
		payParams.put("fee_type", fee_type); // 币种 CNY
		payParams.put("total_fee", String.valueOf(total_fee)); //金额
		payParams.put("spbill_create_ip", spbill_create_ip);//终端IP 218.17.162.203
		payParams.put("time_start", dateFormat.format(new Date()));//交易起始时间
		payParams.put("time_expire", dateFormat.format(new Date()));//交易结束时间
		payParams.put("notify_url", notify_url); //通知地址
		payParams.put("trade_type", trade_type); //交易类型
		payParams.put("product_id", RandomStringUtils.randomNumeric(12));//商品ID
		payParams.put("openid", openid); //用户标识
		String sgin = SignUtils.createSign("UTF-8" ,payParams); 
		payParams.put("sign", sgin);
		String incoming = convertToXML(payParams);
		if (logger.isInfoEnabled()){
			logger.info(incoming);
		}
		try {
			String str = HttpHelpUtils.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", incoming);
			System.out.println(str);
			Map<String, Object> maps = new HashMap<String, Object>();
			maps = xmlElements(str);
			System.out.println(" return_code " + maps.get("return_code"));
			return resultMaps;
		} catch (Exception e){
			if (logger.isInfoEnabled()){
				logger.error("输入输出异常", e);
			} 
			return null;
		}
	}
	
	protected static String convertToXML(SortedMap<String, String> sortedMap){
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (Map.Entry<String, String> entry : sortedMap.entrySet()){
			sb.append("<").append(entry.getKey()).append("><![CDATA[");
			sb.append(entry.getValue()).append("]]></").append(entry.getKey()).append(">");
		}
		sb.append("</xml>");
		return sb.toString();
	}
	
	public static Map<String, Object> xmlElements(String xmlDoc) {
		Map<String, Object> retMaps = new HashMap<String, Object>();
        //创建一个新的字符串
        StringReader read = new StringReader(xmlDoc);
        //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        //创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        try {
            //通过输入源构造一个Document
            Document doc = sb.build(source);
            //取的根元素
            Element root = doc.getRootElement();
            //得到根元素所有子元素的集合
            String return_code = root.getChildText("return_code");
            retMaps.put("return_code", return_code);
            String result_code = root.getChildText("result_code");
            retMaps.put("result_code", result_code);
            retMaps.put("return_msg", root.getChildText("return_msg"));
            retMaps.put("appid", root.getChildText("appid"));
            retMaps.put("mch_id", root.getChildText("mch_id"));
            retMaps.put("sign", root.getChildText("sign"));
            
            //获得XML中的命名空间（XML中未定义可不写）
            if(!xmlDoc.contains("err_code")){
                retMaps.put("prepay_id", root.getChildText("prepay_id"));
            } else {
                retMaps.put("err_code", root.getChildText("err_code"));
                retMaps.put("err_code_des", root.getChildText("err_code_des"));
            }
            return retMaps;
        } catch (JDOMException e) {
        	e.printStackTrace();
        	return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
	
	public static void main(String[] args) {

	}

}
